<template>
  <div class="view-fill">
    <div v-show="!assetDetailInfo.visible" class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :needReturn="!flowFormType"
        @returnBack="$emit('returnModify')"
      >
        <template v-slot:full-button>
          <el-button
            :disabled="!canSave"
            @click="saveAndSubmit()"
            v-if="
              !orderId &&
              $permission('assetTransfer:saveAndSubmit') &&
              !flowFormType
            "
            >保存并提交</el-button
          >
          <el-button v-if="!flowFormType" :disabled="!canSave" @click="save()"
            >保存</el-button
          >
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
            </page-form>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <page-filter :filter-list="filterInfo.list">
              <template v-slot:filter-addAsset>
                <el-button @click="addAsset">添加资产</el-button>
              </template>
              <template v-slot:filter-removeAsset>
                <el-button :disabled="!canRemoveAsset" @click="removeAsset()"
                  >删除资产</el-button
                >
              </template>
              <template v-slot:filter-settingDept>
                <el-button :disabled="!canSettingDept" @click="settingDept()"
                  >批量设置使用部门</el-button
                >
              </template>
              <template v-slot:filter-assetCodeScan>
                <ScanInputBox
                  :query="scanInfo.query"
                  @callback="onCallBackScanData"
                />
              </template>
            </page-filter>
            <div class="flex_full_item">
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <!-- 表格 -->
                <page-table
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :tab-index="true"
                  :isDynamic="true"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-assetName="scope">
                    <span
                      class="slip-edit"
                      @click="showAssetDetail(scope.row)"
                      >{{ scope.row.assetName }}</span
                    >
                  </template>
                  <template v-slot:col-newUseDeptName="scope">
                    <el-input
                      v-model="scope.row.newUseDeptName"
                      style="width: 100%"
                      class="not-mongolia"
                      type="input"
                      :required="true"
                      :disabled="true"
                      :placeholder="'请选择部门'"
                    >
                      <template #append>
                        <el-icon @click="checkNewUseDeptName(scope.row)"
                          ><MoreFilled
                        /></el-icon>
                      </template>
                    </el-input>
                  </template>
                  <template v-slot:col-newManageDeptName="scope">
                    <el-input
                      v-model="scope.row.newManageDeptName"
                      style="width: 100%"
                      class="not-mongolia"
                      type="input"
                      :required="true"
                      :disabled="true"
                      :placeholder="'请选择部门'"
                    >
                      <template #append>
                        <el-icon @click="checkNewManageDeptName(scope.row)"
                          ><MoreFilled
                        /></el-icon>
                      </template>
                    </el-input>
                  </template>
                  <template v-slot:col-newFinanceDeptName="scope">
                    <el-input
                      v-model="scope.row.newFinanceDeptName"
                      style="width: 100%"
                      class="not-mongolia"
                      type="input"
                      :required="true"
                      :disabled="true"
                      :placeholder="'请选择部门'"
                    >
                      <template #append>
                        <el-icon @click="checkNewFinanceDeptName(scope.row)"
                          ><MoreFilled
                        /></el-icon>
                      </template>
                    </el-input>
                  </template>
                  <template v-slot:col-newUseUserName="scope">
                    <el-input
                      v-model="scope.row.newUseUserName"
                      style="width: 100%"
                      class="not-mongolia"
                      type="input"
                      :required="true"
                      :disabled="true"
                      :placeholder="'请选择使用人'"
                    >
                      <template #append>
                        <el-icon @click="checkNewUseUserName(scope.row)"
                          ><MoreFilled
                        /></el-icon>
                      </template>
                    </el-input>
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <!-- 添加资产 -->
    <Select-asset
      v-if="selectAssetInfo.visible"
      v-model:show-dialog="selectAssetInfo.visible"
      :query="selectAssetInfo.query.queryMap"
      :query-params="selectAssetInfo.query.queryParams"
      :check-box="true"
      @callback="callBackAsset"
    />
    <!-- 详情页 -->
    <asset-card-detail
      v-if="assetDetailInfo.visible"
      :id="assetDetailInfo.id"
      v-model:visible="assetDetailInfo.visible"
      :title="assetDetailInfo.title"
    />
    <!-- 选择部门 -->
    <select-dept
      v-if="newUseDeptInfo.visible"
      v-model:show-dialog="newUseDeptInfo.visible"
      :check-box="false"
      :highlight-row="true"
      :query="newUseDeptInfo.query"
      :save-empty="true"
      @callback="callbackNewUseDept"
    />
    <select-dept
      v-if="newManageDeptInfo.visible"
      v-model:show-dialog="newManageDeptInfo.visible"
      :check-box="false"
      :highlight-row="true"
      :query="newManageDeptInfo.query"
      :save-empty="true"
      @callback="callbackNewManageDept"
    />
    <select-dept
      v-if="newFinanceDeptInfo.visible"
      v-model:show-dialog="newFinanceDeptInfo.visible"
      :check-box="false"
      :highlight-row="true"
      :query="newFinanceDeptInfo.query"
      :save-empty="true"
      @callback="callbackNewFinanceDept"
    />
    <!-- 选择人员 -->
    <select-users
      v-if="newUseUserInfo.visible"
      v-model:show-dialog="newUseUserInfo.visible"
      :api="newUseUserInfo.api"
      :save-empty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="callBackNewUseUser"
    />
    <AmortizationAdjust
      v-if="amortizationAdjustInfo.visible"
      v-model:show-dialog="amortizationAdjustInfo.visible"
      :left-data="amortizationAdjustInfo.leftData"
      :right-data="amortizationAdjustInfo.rightData"
      @callback="amortizationAdjustCallback"
    />
    <SettingDept
      v-if="settingDeptInfo.visible"
      v-model:show-dialog="settingDeptInfo.visible"
      @callback="settingDeptCallback"
    />
  </div>
</template>

<script setup name="AssetTransferModify">
import AmortizationAdjust from '../../components/amortizationAdjust'
import SettingDept from './settingDept'
import { getCustomizeSetting } from '@/api/customize'
import ScanInputBox from '@/components/SelectAsset/ScanInputBox'
import {
  updateAssetTranfer,
  refreshAssetTransfer,
  createAssetTranfer,
  createAssetTranferAndSave,
  submitAssetTransfer,
  getAssetTransfer,
  getAssetTransferDetailCustomizeListAll,
} from '@/api/asset'
import { getCurrentFiscalPeriod } from '@/api/core'
import SelectDept from '@/components/SelectDept/index'
import { getRrgUserList } from '@/api/base'
import moment from 'moment'
const AssetCardDetail = defineAsyncComponent(() =>
  import('@/views/asset/assetManage/assetCard/details')
)

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps(['visible', 'title', 'orderId', 'flowFormType', 'id'])

const newUseDeptInfo = ref({
  visible: false,
  query: {
    deptAuth: 'id',
    status: 1,
  },
  row: {},
})
const newManageDeptInfo = ref({
  visible: false,
  query: {
    deptAuth: 'id',
    status: 1,
  },
  row: {},
})
const newFinanceDeptInfo = ref({
  visible: false,
  query: {
    deptAuth: 'id',
    status: 1,
  },
  row: {},
})
const newUseUserInfo = ref({
  visible: false,
  api: getRrgUserList,
  row: {},
})
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const scanInfo = ref({
  query: {
    assetSourceAuth: true,
  },
})
//表单相关
const formInfo = ref({
  ref: null,
  data: {
    businessDate: '',
  },
  fieldList: [
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'date',
      labelTip: '',
      TimePickerOptions: {},
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      maxlength: 200,
    },
  ],
  rules: {
    businessDate: [
      { required: true, message: '请选择业务日期', trigger: 'blur' },
    ],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {
      joinDepotStock: 'YES',
    },
  },
  list: [
    { type: 'slot', value: 'addAsset' },
    { type: 'slot', value: 'removeAsset' },
    { type: 'slot', value: 'settingDept' },
    { type: 'slot', value: 'assetCodeScan' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '150',
    btList: [
      {
        label: '使用部门调整',
        event: adjustDept,
        show: true,
      },
      {
        label: '删除',
        event: removeAsset,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
const selectAssetInfo = ref({
  visible: false,
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      assetSourceAuth: {
        asTbName: 'core_asset,core_asset',
        columnName: 'use_dept_id,depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'assetSourceAuth',
      },
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '3',
      },
      isLocked: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
      assetStatus: {
        queryType: 'IN',
        value: '1,3',
      },
    },
    queryParams: {
      assetSourceAuth: true,
    },
  },
})
const assetDetailInfo = ref({
  visible: false,
  id: '',
  title: '资产详情',
})
const amortizationAdjustInfo = ref({
  visible: false,
  row: {},
  leftData: [],
  rightData: [],
})
const settingDeptInfo = ref({
  visible: false,
})
const formRefs = ref([])

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const canSave = computed(() => {
  return tableInfo.value.data.length
})
const canRemoveAsset = computed(() => {
  return tableInfo.value.selections.length
})
const canSettingDept = computed(() => {
  return tableInfo.value.selections.length
})

onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  proxy.$nextTick(() => {
    if (!props.id && !props.orderId) {
      formInfo.value.fieldList = formInfo.value.fieldList.filter(
        (item) => item.value !== 'orderNo'
      )
    }
  })
})

setData()
function setData() {
  let obj = {
    newUseDeptName: {
      label: '新使用部门',
      value: 'newUseDeptName',
      asValue: 'newUseDeptId',
      componentType: 'select-dept',
      type: 'slot',
      width: '160px',
      show: false,
      hidden: true,
    },
    newManageDeptName: {
      label: '新管理部门',
      value: 'newManageDeptName',
      asValue: 'newManageDeptId',
      componentType: 'select-dept',
      width: '160px',
      type: 'slot',
      show: false,
      hidden: true,
    },
    newFinanceDeptName: {
      label: '新财务部门',
      value: 'newFinanceDeptName',
      asValue: 'newFinanceDeptId',
      componentType: 'select-dept',
      width: '160px',
      type: 'slot',
      show: false,
      hidden: true,
    },
    newLocation: {
      label: '新存放地点',
      value: 'newLocation',
      maxlength: 150,
      componentType: 'input',
      type: 'input',
      show: false,
      hidden: true,
    },
    reason: {
      label: '原因',
      value: 'reason',
      maxlength: 200,
      componentType: 'input',
      type: 'input',
      show: false,
      hidden: true,
    },
    newUseUserName: {
      label: '新使用人',
      value: 'newUseUserName',
      asValue: 'newUseUserId',
      componentType: 'select-user',
      width: '160px',
      type: 'slot',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
  getFiscalPeriod()
}
function getFiscalPeriod() {
  getCurrentFiscalPeriod(2).then((res) => {
    if (res && res.success) {
      let index = formInfo.value.fieldList.findIndex(
        (item) => item.value === 'businessDate'
      )
      let fiscalPeriodName = res.data.name
      if (index > -1) {
        formInfo.value.fieldList[
          index
        ].labelTip = `当前会计期间：${fiscalPeriodName}`
        formInfo.value.fieldList[index].TimePickerOptions = {
          disabledDate(time) {
            return (
              time.getTime() <
              new Date(res.data.startDate).getTime() - 24 * 60 * 60 * 1000
            )
          },
        }
      }
    }
  })
}
function checkNewUseDeptName(row) {
  newUseDeptInfo.value.visible = true
  newUseDeptInfo.value.row = row
}
function callbackNewUseDept(data) {
  let row = newUseDeptInfo.value.row
  row.newUseDeptName = data.name
  row.newUseDeptId = data.id
}
function checkNewManageDeptName(row) {
  newManageDeptInfo.value.visible = true
  newManageDeptInfo.value.row = row
}
function callbackNewManageDept(data) {
  let row = newManageDeptInfo.value.row
  row.newManageDeptName = data.name
  row.newManageDeptId = data.id
}
function checkNewFinanceDeptName(row) {
  newFinanceDeptInfo.value.visible = true
  newFinanceDeptInfo.value.row = row
}
function callbackNewFinanceDept(data) {
  let row = newFinanceDeptInfo.value.row
  row.newFinanceDeptName = data.name
  row.newFinanceDeptId = data.id
}
function checkNewUseUserName(row) {
  newUseUserInfo.value.visible = true
  newUseUserInfo.value.row = row
}
function callBackNewUseUser(data) {
  let row = newUseUserInfo.value.row
  row.newUseUserName = data.name
  row.newUseUser = data.id
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}
function showAssetDetail(row) {
  assetDetailInfo.value.id = row.assetId
  assetDetailInfo.value.visible = true
}
function adjustDept(row) {
  let arr = proxy.$fn.deepClone(row.detailExtList)
  amortizationAdjustInfo.value.leftData = arr.filter(
    (item) => item.valueType === 1
  )
  amortizationAdjustInfo.value.rightData = arr.filter(
    (item) => item.valueType === 2
  )
  amortizationAdjustInfo.value.visible = true
  amortizationAdjustInfo.value.row = row
}
function amortizationAdjustCallback(leftData, data) {
  let row = amortizationAdjustInfo.value.row
  if (data && data.length) {
    let newUseDept = ''
    data.forEach((item, index) => {
      item.assetId = row.assetId
      item.valueType = 2
      item.relationType = 2
      newUseDept += `${item.relationName}-${item.relationValue}${
        index < data.length - 1 ? ',' : ''
      }`
    })
    let index = tableInfo.value.data.findIndex(
      (item) => item.assetId === row.assetId
    )
    if (index > -1) {
      tableInfo.value.data[index].detailExtList = data.concat(leftData)
      tableInfo.value.data[index]['newUseDept'] = newUseDept
    }
  }
}
function settingDept() {
  settingDeptInfo.value.visible = true
}
function settingDeptCallback(data) {
  if (data && data.length) {
    tableInfo.value.selections.forEach((item, index) => {
      let newUseDept = ''
      const leftData = item.detailExtList.filter((item) => item.valueType === 1)
      data.forEach((el, elIndex) => {
        el.assetId = item.assetId
        el.valueType = 2
        el.relationType = 2
        newUseDept += `${el.relationName}-${el.relationValue}${
          elIndex < data.length - 1 ? ',' : ''
        }`
      })
      item.detailExtList = data.concat(leftData)
      item.newUseDept = newUseDept
    })
    // tableInfo.value.data[index].detailExtList = data.concat(leftData)
    // tableInfo.value.data[index]['newUseDept'] = newUseDept
  }
}
function getMain() {
  getAssetTransfer(props.id || props.orderId).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
    }
  })
  filterInfo.value.query.queryMap.orderId.value = props.id || props.orderId
  getList()
}
function getList() {
  getAssetTransferDetailCustomizeListAll(filterInfo.value.query).then((res) => {
    if (res && res.success && res.data.length) {
      tableInfo.value.data = res.data
    }
  })
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
// flowData 外部流程页面调用
function saveAndSubmit(flowData) {
  save(true, flowData)
}
function save(isSaveAndSubmit, obj = {}) {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let api =
      props.id || props.orderId
        ? updateAssetTranfer
        : isSaveAndSubmit === true
        ? createAssetTranferAndSave
        : createAssetTranfer
    let assetName = tableInfo.value.data
      .filter(
        (item) =>
          item.useDeptId === item.newUseDeptId &&
          item.manageDeptId === item.newManageDeptId &&
          item.financeDeptId === item.newFinanceDeptId &&
          item.location === item.newLocation &&
          item.useUser === item.newUseUser &&
          !item.newUseDept
      )
      .map((item) => item.assetName)
    if (assetName.length) {
      proxy.$alert(`资产【${assetName}】未作任何调整`, '操作提示', {
        confirmButtonText: '确定',
      })
      return
    }
    let param = {
      ...formInfo.value.data,
      details: tableInfo.value.data,
    }
    let flowParams = param
    if (isSaveAndSubmit) {
      if (proxy.$route.query.processInstanceId) {
        api = submitAssetTransfer
      }
      flowParams = {
        orderData: param,
        // flowTaskCommentDto和processDefinitionKey为审批流程需要传递的参数
        flowTaskCommentDto: { approvalType: 'submit' },
        processDefinitionKey: 'assetTransfer',
        processInstanceId: obj.processInstanceId,
        taskId: obj.taskId,
      }
    }
    api(flowParams).then((res) => {
      if (res && res.success) {
        showDialog.value = false
        if ((props.id || props.orderId) && res.msgType === 'messageBox') {
          refreshAssetTransfer(infoList.value.data.id).then()
        }
        emits('returnModify', false)
      }
    })
  })
}
//选择资产
function addAsset() {
  if (tableInfo.value.data.length) {
    selectAssetInfo.value.query.queryMap.id.value = tableInfo.value.data
      .map((item) => item.assetId)
      .toString()
  } else {
    selectAssetInfo.value.query.queryMap.id.value = ''
  }
  selectAssetInfo.value.visible = true
}
function onCallBackScanData(data, callback) {
  if (data && data.assetCode) {
    data.assetId = data.id
    data.assetVersion = data.version
    data['newUseDeptId'] = data.useDeptId
    data['useDept'] = data.useDeptNameRate
    data['newUseDeptName'] = data.useDeptName
    data['newManageDeptId'] = data.manageDeptId
    data['newManageDeptName'] = data.manageDeptName
    data['newFinanceDeptId'] = data.financeDeptId
    data['newFinanceDeptName'] = data.financeDeptName
    data['newLocation'] = data.location
    data['newUseUser'] = data.useUser
    data['newUseUserName'] = data.useUserName
    data.amortizationDept = data.assetAmortizationDeptVOValue
    if (data.assetUseDeptVOList && data.assetUseDeptVOList.length) {
      let arr = proxy.$fn.deepClone(data.assetUseDeptVOList)
      let detailExtList = arr.map((row) => {
        return {
          assetId: data.id,
          relationId: row.useDeptId,
          relationValue: row.rate,
          relationName: row.useDeptName,
          valueType: 1,
          relationType: 2,
        }
      })
      data['detailExtList'] = detailExtList
    } else {
      data['detailExtList'] = []
    }
    if (tableInfo.value.data) {
      tableInfo.value.data.forEach((item) => {
        item.isChoice = false
      })
      let index = tableInfo.value.data.findIndex(
        (item) => item.assetCode === data.assetCode
      )
      if (index !== -1) {
        callback(true)
      } else {
        tableInfo.value.data.unshift(data)
        callback(false)
      }
    } else {
      tableInfo.value.data.unshift(data)
      callback(true)
    }
  }
}
function callBackAsset(data) {
  data.forEach((item) => {
    item.assetId = item.id
    item.assetVersion = item.version
    item['newUseDeptId'] = item.useDeptId
    item['useDept'] = item.useDeptNameRate
    item['newUseDeptName'] = item.useDeptName
    item['newManageDeptId'] = item.manageDeptId
    item['newManageDeptName'] = item.manageDeptName
    item['newFinanceDeptId'] = item.financeDeptId
    item['newFinanceDeptName'] = item.financeDeptName
    item['newLocation'] = item.location
    item['newUseUser'] = item.useUser
    item['newUseUserName'] = item.useUserName
    item.amortizationDept = item.assetAmortizationDeptVOValue
    if (item.assetUseDeptVOList && item.assetUseDeptVOList.length) {
      let arr = proxy.$fn.deepClone(item.assetUseDeptVOList)
      let detailExtList = arr.map((row) => {
        return {
          assetId: item.id,
          relationId: row.useDeptId,
          relationValue: row.rate,
          relationName: row.useDeptName,
          valueType: 1,
          relationType: 2,
        }
      })
      item['detailExtList'] = detailExtList
    } else {
      item['detailExtList'] = []
    }
  })

  tableInfo.value.data = data.concat(tableInfo.value.data)
  console.log(tableInfo.value.data)
}
//删除资产
function removeAsset(selectRow = undefined) {
  if (selectRow) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
function getCustomize() {
  let param = {
    tableKey:
      'assetTransferModify-com.slip.spd.entity.vo.asset.AssetTransferDetailVO',
  }
  tableInfo.value.isSysGroup = false
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      filterInfo.value.query.customizeUserVO = data
      if (props.id || props.orderId) {
        getMain()
      }
    }
  })
}
// 名称不要做改变，在流程引擎中需要通过refs进行调用
defineExpose({
  save,
  saveAndSubmit,
})
</script>

<style scoped lang="scss">
:deep(.page-table) > .el-table {
  overflow: hidden;
}
</style>
